package com.example.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.model.Token;
import com.example.service.TokenService;
import com.example.util.StringUtil;


//验证token接口
@RestController
public class TokenController {
	
	@Autowired
	private TokenService tokenService;
	
	/**
	 * 请求登录到初始化页面
	 */
	@RequestMapping("/tokenVerify")
	public String tokenVerify(String token) {
		if (StringUtil.isBlank(token)) {
			return ""+false;
		}
		System.out.println("进入sso token校验");
		Token token2 =null;
		try {
			String tokenValue = URLDecoder.decode(token, "utf-8");
			 token2 = tokenService.getTokenByValue(tokenValue);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//查看数据库中是否存在该token，并判断是否过期
		boolean result=checkTokenEffective(token2);
		System.out.println("token校验结果："+result);
		return StringUtil.null2Str(result);
	}

	private  boolean checkTokenEffective(Token token2) {
		if (StringUtil.isBlank(token2)) {
			return false;
		}
		String tokenValue = token2.getTokenValue();
		try {
			String[] strings = tokenValue.split("#");
			String oldTimeStamp=strings[1];
			String expireTime=strings[2];
			Long nowTime=System.currentTimeMillis();
			long desTime=Long.parseLong(oldTimeStamp)+(Long.parseLong(expireTime)*1000);
			return desTime-nowTime>0l;
		} catch (Exception e) {
			return false;
		}
		
	}
	

}
